import express from "express";
import { ObjectId } from "mongodb";
import authMiddleware from "../middleware/auth.js";
import { getDb } from "../config/database.js";

const router = express.Router();
const COLLECTION = "customers";

// 获取客户列表
router.get("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { page = 1, limit = 10, search = "", status = "" } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 构建查询条件
    const query = {};

    if (search) {
      query.$or = [
        { name: { $regex: search, $options: "i" } },
        { alias: { $regex: search, $options: "i" } },
        { phone: { $regex: search, $options: "i" } },
        { wechat: { $regex: search, $options: "i" } },
      ];
    }

    if (status) {
      query.status = status;
    }

    // 查询数据
    const customers = await db
      .collection(COLLECTION)
      .find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(Number(limit))
      .toArray();

    // 添加虚拟字段 displayName
    customers.forEach((customer) => {
      customer.displayName = customer.alias
        ? `${customer.name}(${customer.alias})`
        : customer.name;
    });

    // 获取总数
    const total = await db.collection(COLLECTION).countDocuments(query);

    res.json({
      customers,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit)),
    });
  } catch (error) {
    console.error("获取客户列表失败:", error);
    res.status(500).json({ error: "获取客户列表失败" });
  }
});

// 创建客户
router.post("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      name,
      alias,
      phone,
      wechat,
      prepaidAmount,
      transactionMethods,
      shippingAddresses,
      idCardFront,
      idCardBack,
      status,
    } = req.body;

    // 验证必填字段
    if (
      !name ||
      !phone ||
      prepaidAmount === undefined ||
      prepaidAmount === null
    ) {
      return res
        .status(400)
        .json({ error: "姓名、手机号和面单预充金额为必填项" });
    }

    // 检查姓名+手机号是否已存在
    const existingCustomer = await db
      .collection(COLLECTION)
      .findOne({ name, phone });

    if (existingCustomer) {
      return res.status(400).json({
        error: `客户"${name}"的手机号"${phone}"已存在，请检查是否重复添加`,
      });
    }

    // 创建新客户
    const newCustomer = {
      name,
      alias: alias || "",
      phone,
      wechat: wechat || "",
      prepaidAmount: Number(prepaidAmount) || 0,
      transactionMethods: transactionMethods || [],
      shippingAddresses: shippingAddresses || [],
      idCardFront: idCardFront || "",
      idCardBack: idCardBack || "",
      status: status || "active",
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await db.collection(COLLECTION).insertOne(newCustomer);

    // 添加虚拟字段 displayName
    newCustomer._id = result.insertedId;
    newCustomer.displayName = newCustomer.alias
      ? `${newCustomer.name}(${newCustomer.alias})`
      : newCustomer.name;

    res.status(201).json(newCustomer);
  } catch (error) {
    console.error("创建客户失败:", error);

    // 处理唯一索引冲突错误
    if (error.code === 11000) {
      return res.status(400).json({
        error: `客户"${req.body.name}"的手机号"${req.body.phone}"已存在，请检查是否重复添加`,
      });
    }

    res.status(500).json({ error: "创建客户失败" });
  }
});

// 更新客户
router.put("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { id } = req.params;
    const {
      name,
      alias,
      phone,
      wechat,
      prepaidAmount,
      transactionMethods,
      shippingAddresses,
      idCardFront,
      idCardBack,
      status,
    } = req.body;

    // 验证必填字段
    if (
      !name ||
      !phone ||
      prepaidAmount === undefined ||
      prepaidAmount === null
    ) {
      return res
        .status(400)
        .json({ error: "姓名、手机号和面单预充金额为必填项" });
    }

    // 检查姓名+手机号是否已被其他客户使用
    const existingCustomer = await db.collection(COLLECTION).findOne({
      name,
      phone,
      _id: { $ne: new ObjectId(id) },
    });

    if (existingCustomer) {
      return res.status(400).json({
        error: `客户"${name}"的手机号"${phone}"已被其他客户使用`,
      });
    }

    // 更新客户
    const updateData = {
      $set: {
        name,
        alias: alias || "",
        phone,
        wechat: wechat || "",
        prepaidAmount: Number(prepaidAmount) || 0,
        transactionMethods: transactionMethods || [],
        shippingAddresses: shippingAddresses || [],
        idCardFront: idCardFront || "",
        idCardBack: idCardBack || "",
        status: status || "active",
        updatedAt: new Date(),
      },
    };

    const result = await db
      .collection(COLLECTION)
      .findOneAndUpdate({ _id: new ObjectId(id) }, updateData, {
        returnDocument: "after",
      });

    if (!result) {
      return res.status(404).json({ error: "客户不存在" });
    }

    // 添加虚拟字段 displayName
    const updatedCustomer = result;
    updatedCustomer.displayName = updatedCustomer.alias
      ? `${updatedCustomer.name}(${updatedCustomer.alias})`
      : updatedCustomer.name;

    res.json(updatedCustomer);
  } catch (error) {
    console.error("更新客户失败:", error);

    // 处理唯一索引冲突错误
    if (error.code === 11000) {
      return res.status(400).json({
        error: `客户"${req.body.name}"的手机号"${req.body.phone}"已被其他客户使用`,
      });
    }

    res.status(500).json({ error: "更新客户失败" });
  }
});

// 获取单个客户
router.get("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const customer = await db
      .collection(COLLECTION)
      .findOne({ _id: new ObjectId(req.params.id) });

    if (!customer) {
      return res.status(404).json({ error: "客户不存在" });
    }

    // 添加虚拟字段 displayName
    customer.displayName = customer.alias
      ? `${customer.name}(${customer.alias})`
      : customer.name;

    res.json(customer);
  } catch (error) {
    console.error("获取客户失败:", error);
    res.status(500).json({ error: "获取客户失败" });
  }
});

// 删除客户
router.delete("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();

    // 检查是否有关联的店铺
    const relatedShops = await db
      .collection("shops")
      .countDocuments({ customerId: new ObjectId(req.params.id) });
    if (relatedShops > 0) {
      return res
        .status(400)
        .json({ error: "该客户下还有店铺，请先删除相关店铺" });
    }

    const result = await db
      .collection(COLLECTION)
      .findOneAndDelete({ _id: new ObjectId(req.params.id) });

    if (!result) {
      return res.status(404).json({ error: "客户不存在" });
    }

    res.json({ message: "客户删除成功" });
  } catch (error) {
    console.error("删除客户失败:", error);
    res.status(500).json({ error: "删除客户失败" });
  }
});

// 检查姓名+手机号是否重复
router.post("/check-duplicate", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { name, phone, excludeId } = req.body;

    const query = { name, phone };
    if (excludeId) {
      query._id = { $ne: new ObjectId(excludeId) };
    }

    const existingCustomer = await db.collection(COLLECTION).findOne(query);

    res.json({
      isDuplicate: !!existingCustomer,
      message: existingCustomer
        ? `客户"${name}"的手机号"${phone}"已存在`
        : "姓名和手机号组合可用",
    });
  } catch (error) {
    console.error("检查重复失败:", error);
    res.status(500).json({ error: "检查重复失败" });
  }
});

export default router;
